package com.sky.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.BaseException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.service.UserService;
import com.sky.service.WechatService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zzw
 * @date 2025/5/16
 * @description 用户服务实现类
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WechatService wechatService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户登录
     *
     * @param userLoginDTO 登录信息
     * @return UserLoginVO
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {

        // 1.  获取微信openid
        String openid = wechatService.getOpenid(userLoginDTO.getCode());
        if (ObjectUtil.isEmpty(openid)) {
            throw new BaseException("请先登录");
        }

        // 2.根据openid查询用户
        User user = userMapper.getByOpenid(openid);
        if (ObjectUtil.isNull(user)) {
            user = User.builder()
                       .openid(openid)
                       .createTime(LocalDateTime.now())
                       .build();
            userMapper.insert(user);
        }

        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        return UserLoginVO.builder()
                          .id(user.getId())
                          .openid(user.getOpenid())
                          .token(token)
                          .build();

    }
}
